<?php


namespace plugins\api\controller;

use app\BaseController as AppBaseController;
use app\model\Theme;
use app\model\Website;
use app\service\ApiService;
use think\facade\Cache;

class BaseController extends AppBaseController
{
    protected $domain;
    protected $siteId;
    protected $sellerId;
    protected $theme;
    protected $lang;
    protected $parentSiteId;
    protected $realSiteId;

    public function initialize()
    {
        parent::initialize();

        $this->setCommonParam();
        $this->setRealSiteId();
        $this->getActiveTheme();
    }

    /**
     * @throws \app\exception\ModelException
     */
    public function setCommonParam()
    {
        $domain = $this->request->host();
        $Website = new Website();
        $website = $Website->getWebsiteByDomain($domain,'id,domain,seller_id,parent_id,status')['data'];

        if ($website['status'] == 2) {
            return jsonReturn(-404, lang('网站信息不存在'));
        }

        $this->domain = $domain;
        $this->siteId = $website['id'];
        $this->parentSiteId = $website['parent_id'];
        $this->sellerId = $website['seller_id'];
        $this->lang = setLang();
    }

    /**
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function getActiveTheme()
    {
        $Theme = new Theme();
        $theme = $Theme->getActiveTheme(['seller_id'=>$this->sellerId,'website_id'=>$this->realSiteId,'lang'=>$this->lang,'is_active'=>1])['data']->toArray();
        $cacheKey = $this->sellerId .'_'.$this->siteId .'_'. $this->lang . '_website_cache_key';
        $settingData = Cache::get($cacheKey);
        if(empty($settingData)){
            $settingData = ApiService::setWebsiteSetting($this->sellerId,$this->siteId,$this->lang);
        }
        $this->settingData = $settingData;

        if(isMobile() && !empty($settingData['common_template']) && $settingData['common_template'] == 2){
            $this->theme = 'm_' . $theme['theme'];
        }else{
            $this->theme = $theme['theme'];
        }
    }

    public function setRealSiteId()
    {
        $siteId = $this->siteId;
        if($this->parentSiteId){
            $siteId = $this->parentSiteId;
        }
        return $this->realSiteId = $siteId;
    }
}
